
import { IndexImagePainter } from '../../../common/image';
import { TextureLoader } from '../../../common/image/textureLoader';

class AvatarSheet {
  url = '';
  /** @type {AvatarDetail[]} */
  instances = [];
  loaded = false;
  loader = new TextureLoader();

  loadImage() {
    if (this.loaded) {
      return Promise.resolve(this);
    }

    return this.loader.load(this.url)
      .then(() => {
        const sheet = this.loader.findSheet(this.url);
        const textureMap = sheet.allFromCache();
        for (let name in textureMap) {
          const instance = this.instances.find(i => i.name == name);
          if (instance == null) return;

          instance.painter = textureMap[name].createPainter();
          let def = sheet.findTextureDefine(name);
          instance.offx = def.offx;
          instance.offy = def.offy;
        }
        this.loaded = true;
        return this;
      });
  }
}

class AvatarDetail {
  name = '';
  details = '';
  detailsCh = '';
  HP = 0;
  AT = 3;
  /** @type {string[]} */
  weakness = [];

  /** @type {IndexImagePainter} */
  painter = null;
  /** @type {HTMLCanvasElement} 未选中时的 */
  avatar = null;
  /** @type {HTMLCanvasElement} 选中时的 */
  avatar2 = null;
  offx = 0;
  offy = 0;
}


/** @type {AvatarSheet[]} */
let cacheSheets;

function loadAvatarDetails(context) {
  if (cacheSheets) {
    return Promise.resolve(cacheSheets);
  }

  const url = context.assetPath('assets/codex/avatar_details.json');
  return fetch(url)
    .then(d => d.json())
    .then(d => {
      /** @type {AvatarSheet[]} */
      let sheets = d.bundles.map(dd => {
        let sheet = new AvatarSheet();
        sheet.url = url.substring(0, url.lastIndexOf('/')) + '/' + dd.sheet;
        sheet.instances = dd.instances.map(i => {
          let detail = new AvatarDetail();
          Object.assign(detail, i);
          return detail;
        });
        return sheet;
      });
      return cacheSheets = sheets;
    })
    .then(sheets => {
      return Promise.all(sheets.map(s => s.loadImage()));
    });
}

export {
  AvatarSheet, AvatarDetail,
  loadAvatarDetails,
};
